﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;
using System.IO;

namespace ZipUp
{
    static class  EasySerializationHelper
    {
        public static IDictionary<Type, XmlSerializer> Serializers = new Dictionary<Type, XmlSerializer>();

        public static T FromXmlStream<T>(Stream stream)
        {
            if (!Serializers.ContainsKey(typeof(T)))
            {
                Serializers.Add(typeof(T), new XmlSerializer(typeof(T)));
            }
            return (T)Serializers[typeof(T)].Deserialize(stream);
        }
        
        public static T FromXmlFile<T>(string fileName)
        {
            return FromXmlStream<T>(new FileStream(fileName, FileMode.Open));
        }

        //public static List<Job> BulkFromXmlStream<Job>(Stream stream)
        //{
        //    if (!Serializers.ContainsKey(typeof(List<Job>)))
        //    {
        //        Serializers.Add(typeof(List<Job>), new XmlSerializer(typeof(List<Job>), new XmlRootAttribute("Jobs")));
        //    }
        //    return (List<Job>)Serializers[typeof(List<Job>)].Deserialize(stream);
        //}

        //public static List<T> BulkFromXmlStream<T>(Stream stream) where T : IEasySerializable 
        //{
        //    if (!Serializers.ContainsKey(typeof(List<T>)))
        //    {
        //        Serializers.Add(typeof(List<T>), new XmlSerializer(typeof(List<T>)));
        //    }
        //    return (List<T>)Serializers[typeof(List<T>)].Deserialize(stream);
        //}

        //public static List<T> BulkFromXmlFile<T>(string fileName) where T : IEasySerializable
        //{
        //    return BulkFromXmlStream<T>(new FileStream(fileName, FileMode.Open));
        //}

        public static void Serialize<T>(this T obj, Stream stream) where T : IEasySerializable
        {
            if (!Serializers.ContainsKey(typeof(T)))
            {
                Serializers.Add(typeof(T), new XmlSerializer(typeof(T)));
            }
            Serializers[typeof(T)].Serialize(stream, obj);
        }
        
        public static void Serialize<T>(this T obj, TextWriter textWriter) where T : IEasySerializable
        {
            if (!Serializers.ContainsKey(typeof(T)))
            {
                Serializers.Add(typeof(T), new XmlSerializer(typeof(T)));
            }
            Serializers[typeof(T)].Serialize(textWriter, obj);
        }
    }
}
